// 主应用逻辑
// 当页面加载完成后的初始化函数
// 当页面加载完成后的初始化函数
document.addEventListener('DOMContentLoaded', () => {
    // 当前时间显示
    updateCurrentTime();
    setInterval(updateCurrentTime, 1000);
    
    // 任务列表功能
    initTaskList();
    
    // 时间设置功能
    initTimeSettings();
    
    // 成就展示功能
    initAchievementView();
    
    // 紧急模式按钮
    document.getElementById('emergency-btn').addEventListener('click', toggleEmergencyMode);
    document.getElementById('close-emergency').addEventListener('click', toggleEmergencyMode);
    
    // Excel假交互
    initExcelInteraction();
    
    // 快捷键支持
    document.addEventListener('keydown', handleKeyPress);
    
    // 加载保存的设置
    loadSettings();
    
    // 显示提示消息
    setTimeout(() => {
        showAchievementPopup('欢迎使用', 'FishTime+ 已准备就绪，开始高效工作与休息！');
    }, 1000);
});

// Excel假交互功能
function initExcelInteraction() {
    // 点击单元格选中效果
    document.querySelectorAll('.excel-cell').forEach(cell => {
        cell.addEventListener('click', () => {
            // 移除之前的选中状态
            document.querySelectorAll('.excel-cell.selected').forEach(selectedCell => {
                selectedCell.classList.remove('selected');
            });
            
            // 添加新的选中状态
            cell.classList.add('selected');
            
            // 更新公式栏的单元格地址
            const row = cell.parentElement.querySelector('.row-header').textContent;
            const col = Array.from(cell.parentElement.children).indexOf(cell) - 1;
            const colLetter = String.fromCharCode(65 + col); // 将数字转换为字母 (0 -> A, 1 -> B, etc.)
            
            document.querySelector('.cell-address').textContent = colLetter + row;
            
            // 更新公式栏的值
            const input = document.querySelector('.excel-formula-bar input');
            if (cell.classList.contains('formula')) {
                input.value = '=SUM(' + colLetter + '2:' + colLetter + '4)';
            } else {
                input.value = cell.textContent;
            }
        });
    });
    
    // 工作表选项卡切换
    document.querySelectorAll('.sheet-tab').forEach(tab => {
        tab.addEventListener('click', () => {
            document.querySelectorAll('.sheet-tab').forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
        });
    });
    
    // Excel菜单点击
    document.querySelectorAll('.excel-menu-bar div').forEach(menu => {
        menu.addEventListener('click', () => {
            // 只是为了交互效果，不做实际功能
            menu.style.backgroundColor = 'rgba(255, 255, 255, 0.2)';
            setTimeout(() => {
                menu.style.backgroundColor = '';
            }, 300);
        });
    });
    
    // 工具栏按钮点击
    document.querySelectorAll('.tool-group button').forEach(button => {
        button.addEventListener('click', () => {
            button.style.backgroundColor = '#d0d0d0';
            setTimeout(() => {
                button.style.backgroundColor = '';
            }, 300);
        });
    });
    
    // 窗口控制按钮交互
    document.querySelector('.minimize-btn').addEventListener('click', () => {
        // 模拟最小化效果
        const overlay = document.getElementById('emergency-overlay');
        overlay.style.opacity = '0';
        setTimeout(() => {
            overlay.style.display = 'none';
            overlay.style.opacity = '1';
        }, 300);
    });
    
    document.querySelector('.maximize-btn').addEventListener('click', () => {
        // 模拟最大化/还原效果
        const btn = document.querySelector('.maximize-btn i');
        if (btn.classList.contains('fa-window-maximize')) {
            btn.classList.remove('fa-window-maximize');
            btn.classList.add('fa-window-restore');
        } else {
            btn.classList.remove('fa-window-restore');
            btn.classList.add('fa-window-maximize');
        }
    });
}

// 更新当前时间
function updateCurrentTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    
    document.getElementById('current-time').textContent = `${hours}:${minutes}:${seconds}`;
}

// 任务列表功能
function initTaskList() {
    const addTaskBtn = document.getElementById('add-task-btn');
    const newTaskInput = document.getElementById('new-task');
    const taskList = document.getElementById('task-list');
    
    // 加载保存的任务
    loadTasks();
    
    // 添加新任务
    addTaskBtn.addEventListener('click', () => {
        addTask(newTaskInput.value);
    });
    
    // 回车添加任务
    newTaskInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            addTask(newTaskInput.value);
        }
    });
    
    // 监听任务完成事件
    taskList.addEventListener('change', (e) => {
        if (e.target.type === 'checkbox') {
            const completedTasks = document.querySelectorAll('#task-list input[type="checkbox"]:checked').length;
            document.getElementById('tasks-completed').textContent = completedTasks;
            
            // 保存任务状态
            saveTasks();
            
            // 检查成就
            if (completedTasks >= 5) {
                showAchievementPopup('效率专家', '完成了5个任务');
            }
        }
    });
    
    // 使用事件委托监听删除按钮点击
    taskList.addEventListener('click', function(e) {
        // 检查点击的是否是删除按钮或其子元素
        if (e.target.classList.contains('delete-task') || e.target.closest('.delete-task')) {
            // 获取包含该按钮的任务项
            const taskItem = e.target.closest('li');
            if (taskItem) {
                // 从DOM中移除任务项
                taskItem.remove();
                
                // 保存更新后的任务列表
                saveTasks();
                
                // 更新已完成任务计数
                const completedTasks = document.querySelectorAll('#task-list input[type="checkbox"]:checked').length;
                document.getElementById('tasks-completed').textContent = completedTasks;
            }
        }
    });
}


// 添加新任务
function addTask(text) {
    if (!text.trim()) return;
    
    const taskList = document.getElementById('task-list');
    const newTaskInput = document.getElementById('new-task');
    
    const taskId = 'task' + Date.now();
    
    const li = document.createElement('li');
    li.innerHTML = `
        <input type="checkbox" id="${taskId}">
        <label for="${taskId}">${text}</label>
        <button class="delete-task" title="删除任务"><i class="fas fa-trash"></i></button>
    `;
    
    taskList.appendChild(li);
    newTaskInput.value = '';
    newTaskInput.focus();
    
    // 保存任务
    saveTasks();
}

// 保存任务到本地存储
function saveTasks() {
    const taskItems = [];
    
    document.querySelectorAll('#task-list li').forEach(li => {
        const checkbox = li.querySelector('input[type="checkbox"]');
        const label = li.querySelector('label');
        
        if (checkbox && label) {
            taskItems.push({
                id: checkbox.id,
                text: label.textContent,
                completed: checkbox.checked
            });
        }
    });
    
    localStorage.setItem('fishtime-tasks', JSON.stringify(taskItems));
}

// 加载保存的任务
function loadTasks() {
    const savedTasks = localStorage.getItem('fishtime-tasks');
    if (!savedTasks) return;
    
    const taskList = document.getElementById('task-list');
    taskList.innerHTML = '';
    
    try {
        const tasks = JSON.parse(savedTasks);
        
        tasks.forEach(task => {
            const li = document.createElement('li');
            li.innerHTML = `
                <input type="checkbox" id="${task.id}" ${task.completed ? 'checked' : ''}>
                <label for="${task.id}">${task.text}</label>
                <button class="delete-task" title="删除任务"><i class="fas fa-trash"></i></button>
            `;
            
            taskList.appendChild(li);
        });
        
        // 更新已完成任务计数
        const completedTasks = document.querySelectorAll('#task-list input[type="checkbox"]:checked').length;
        document.getElementById('tasks-completed').textContent = completedTasks;
    } catch (error) {
        console.error('加载任务时出错:', error);
    }
}

// 切换紧急模式
function toggleEmergencyMode() {
    const overlay = document.getElementById('emergency-overlay');
    overlay.style.display = overlay.style.display === 'block' ? 'none' : 'block';
    
    if (overlay.style.display === 'block') {
        // 如果是第一次使用紧急模式，解锁成就
        if (!localStorage.getItem('emergency-used')) {
            localStorage.setItem('emergency-used', 'true');
            showAchievementPopup('快速隐藏', '成功使用了紧急模式');
        }
    }
}

// 处理键盘快捷键
function handleKeyPress(e) {
    // Esc 键触发紧急模式
    if (e.key === 'Escape') {
        toggleEmergencyMode();
    }
    
    // Ctrl+B 切换休息模式
    if (e.ctrlKey && e.key === 'b') {
        e.preventDefault();
        document.getElementById('break-mode-btn').click();
    }
    
    // Ctrl+W 切换工作模式
    if (e.ctrlKey && e.key === 'w') {
        e.preventDefault();
        document.getElementById('work-mode-btn').click();
    }
}

// 保存应用设置
function saveSettings() {
    const settings = {
        workDuration: timerConfig.workDuration,
        breakDuration: timerConfig.breakDuration
    };
    
    localStorage.setItem('fishtime-settings', JSON.stringify(settings));
}

// 加载应用设置
function loadSettings() {
    const savedSettings = localStorage.getItem('fishtime-settings');
    if (!savedSettings) return;
    
    const settings = JSON.parse(savedSettings);
    
    if (settings.workDuration) {
        timerConfig.workDuration = settings.workDuration;
    }
    
    if (settings.breakDuration) {
        timerConfig.breakDuration = settings.breakDuration;
    }
    
    // 重置计时器以应用新设置
    timerConfig.currentTime = timerConfig.workDuration;
    updateTimerDisplay();
}
// 添加自定义时间设置
function initTimeSettings() {
    // 创建设置按钮
    const settingsBtn = document.createElement('button');
    settingsBtn.innerHTML = '<i class="fas fa-cog"></i>';
    settingsBtn.className = 'settings-btn';
    settingsBtn.title = '设置时间';
    
    // 添加到计时器控制区域
    document.querySelector('.timer-controls').appendChild(settingsBtn);
    
    // 创建设置面板
    const settingsPanel = document.createElement('div');
    settingsPanel.className = 'settings-panel';
    settingsPanel.innerHTML = `
        <div class="settings-header">
            <h3>时间设置</h3>
            <button class="close-settings"><i class="fas fa-times"></i></button>
        </div>
        <div class="settings-body">
            <div class="setting-item">
                <label for="work-time">工作时长 (分钟):</label>
                <input type="number" id="work-time" min="1" max="120" value="${timerConfig.workDuration / 60}">
            </div>
            <div class="setting-item">
                <label for="break-time">休息时长 (分钟):</label>
                <input type="number" id="break-time" min="1" max="60" value="${timerConfig.breakDuration / 60}">
            </div>
            <button class="save-settings">保存设置</button>
        </div>
    `;
    
    // 添加到页面
    document.querySelector('.app-container').appendChild(settingsPanel);
    
    // 打开设置面板
    settingsBtn.addEventListener('click', () => {
        settingsPanel.classList.add('show');
    });
    
    // 关闭设置面板
    document.querySelector('.close-settings').addEventListener('click', () => {
        settingsPanel.classList.remove('show');
    });
    
    // 保存设置
    document.querySelector('.save-settings').addEventListener('click', () => {
        const workTimeMinutes = parseInt(document.getElementById('work-time').value);
        const breakTimeMinutes = parseInt(document.getElementById('break-time').value);
        
        if (workTimeMinutes >= 1 && breakTimeMinutes >= 1) {
            timerConfig.workDuration = workTimeMinutes * 60;
            timerConfig.breakDuration = breakTimeMinutes * 60;
            
            // 如果当前是工作时间，更新当前时间
            if (!timerConfig.isBreakTime) {
                timerConfig.currentTime = timerConfig.workDuration;
            } else {
                timerConfig.currentTime = timerConfig.breakDuration;
            }
            
            // 重置计时器
            resetTimer();
            updateTimerDisplay();
            
            // 保存设置
            saveSettings();
            
            // 关闭面板
            settingsPanel.classList.remove('show');
            
            // 显示成功消息
            showAchievementPopup('自定义达人', '成功自定义了时间设置');
        } else {
            alert('请输入有效的时间（最小1分钟）');
        }
    });
}